//
//  JXAppleIDLoginTools.swift
//  GodoxFlash
//
//  Created by godox on 2021/12/1.
//


import UIKit
import AuthenticationServices

/// AppleId 登录
@available(iOS 13.0, *)
public class JXAppleIDLoginTools: NSObject {
    
    public static let shared = JXAppleIDLoginTools()
    
    /// 失败回调
    private var failureHandle:((_ errorString: String) -> Void)?
    
    /// 成功回调
    private var sucessHandle:((_ identityToken: Data,  _ authorizationCode: Data, _ user: String) -> Void)?
}

@available(iOS 13.0, *)
extension JXAppleIDLoginTools {
    
    /// 登录苹果ID
    /// - Parameters:
    ///   - sucessHandle: 成功回调
    ///   - failureHandle: 失败回调
    public func loginAppleId(sucessHandle:(( _ identityToken: Data,
                                      _ authorizationCode: Data,
                                      _ user: String) -> Void)?,
                      failureHandle:(( _ errorString: String) -> Void)?) {
        self.sucessHandle = sucessHandle
        self.failureHandle = failureHandle
        //基于用户的Apple ID 授权用户，生成用户授权请求的一种机制
        let appleIdProvider =  ASAuthorizationAppleIDProvider()
        //创建新的Apple ID授权请求
        let request = appleIdProvider.createRequest()
        //在用户授权期间请求的联系信息
        request.requestedScopes = [ASAuthorization.Scope.email, ASAuthorization.Scope.fullName]
        //由ASAuthorizationAppleIDProvider创建的授权请求，管理授权请求的控制器
        let controller = ASAuthorizationController.init(authorizationRequests: [request])
        //设置授权控制器通知授权请求的成功与失败的代理
        controller.delegate = self;
        //提供展示上下文的代理，在这个上下文中，系统可以展示授权界面给用户
        controller.presentationContextProvider = self;
        controller.performRequests()
    }
    
    //MARK:暂未测试
//    // 如果存在iCloud Keychain 凭证或者AppleID 凭证提示用户
//    func perfomExistingAccountSetupFlows() {
//        // 基于用户的Apple ID授权用户，生成用户授权请求的一种机制
//        if #available(iOS 13.0, *) {
//            let appleIDProvide = ASAuthorizationAppleIDProvider()
//            // 授权请求AppleID
//            let request = appleIDProvide.createRequest()
//            // 为了执行钥匙串凭证分享生成请求的一种机制
//            let passwordProvider = ASAuthorizationPasswordProvider()
//            let passwordRequest = passwordProvider.createRequest()
//            // 由ASAuthorizationAppleIDProvider创建的授权请求 管理授权请求的控制器
//            let controller = ASAuthorizationController.init(authorizationRequests: [request,passwordRequest])
//            // 设置授权控制器通知授权请求的成功与失败的代理
//            controller.delegate = self
//            // 设置提供 展示上下文的代理，在这个上下文中 系统可以展示授权界面给用户
//            controller.presentationContextProvider = self
//            // 在控制器初始化期间启动授权流
//            controller.performRequests()
//        }
//    }
//
//    private func loginWithServer(user:String,token:String,code:String) {
//        //向你的服务器验证 ,验证通过即可登录
//    }
}
//MARK: - 代理 ASAuthorizationControllerDelegate 处理数据回调
@available(iOS 13.0, *)
extension JXAppleIDLoginTools: ASAuthorizationControllerDelegate {

    //授权成功地回调
    
    public func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if  let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential{
            let identityToken = appleIDCredential.identityToken ?? Data()
            let authorizationCode = appleIDCredential.authorizationCode ?? Data()
            let user = appleIDCredential.user
            sucessHandle?(identityToken, authorizationCode, user)
//            // 使用过授权的，可能获取不到以下三个参数
//            let familyName = appleIDCredential.fullName?.familyName ?? ""
//            let givenName = appleIDCredential.fullName?.givenName ?? ""
//            let email = appleIDCredential.email ?? ""
            
//            // 用于判断当前登录的苹果账号是否是一个真实用户，取值有：unsupported、unknown、likelyReal
//            let realUserStatus = appleIDCredential.realUserStatus
            
        }
        //MARK:暂未测试
//        else if let passworCreddential = authorization.credential as? ASPasswordCredential{
//            // 这个获取的是iCloud记录的账号密码，需要输入框支持iOS 12 记录账号密码的新特性，如果不支持，可以忽略
//            // Sign in using an existing iCloud Keychain credential.
//            // 用户登录使用现有的密码凭证
//            // 密码凭证对象的用户标识 用户的唯一标识
//            let user = passworCreddential.user
//            // 密码凭证对象的密码
//            let password = passworCreddential.password
//        }else{
//            // "授权信息不符合"
//        }
    }
    

    public func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        var errorStr : String?
          switch (error as NSError).code {
              case ASAuthorizationError.canceled.rawValue :
                  errorStr = "用户取消了授权请求"
              case ASAuthorizationError.failed.rawValue :
                  errorStr = "授权请求失败"
              case ASAuthorizationError.invalidResponse.rawValue :
                  errorStr = "授权请求无响应"
              case ASAuthorizationError.notHandled.rawValue :
                  errorStr = "未能处理授权请求"
              case ASAuthorizationError.unknown.rawValue :
                  errorStr = "授权请求失败原因未知"
          default:
              break
          }
          if let errorStr = errorStr {
            failureHandle?(errorStr)
          }
    }
}

//MARK: - 代理 ASAuthorizationControllerPresentationContextProviding 管理视图弹出在哪里
@available(iOS 13.0, *)
extension JXAppleIDLoginTools: ASAuthorizationControllerPresentationContextProviding {

    public func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return JXUITools.getWindows!
    }
}
